<?php
require_once "functions.php";
$db = open_connection_pdo();

if ( isset( $_POST ) ) {
	if ( isset( $_POST['action'] ) and $_POST['action'] == "create_test" ) {
	
		$sigh = array (
					"errors"	=>	"yes" 
				);
		if ( ! isset ( $_POST["test_name"] ) or empty($_POST["test_name"]) ) {
			array_push( $sigh, "Error: Please provide a valid name for this test." );
		}
		
		if ( ! isset ( $_POST["test_purpose"] ) or empty( $_POST["test_purpose"] ) ) {
			array_push( $sigh, "Warning: It is better to explain the purpose of the test." );
		}
				
		if ( isset ( $_POST['strict'] ) and ( $_POST['strict'] == "on" ) )  {
			if ( isset ( $_POST['time'] ) and  ( empty ( $_POST['time'] ) or ( $_POST['time'] <= 0 ) ) ) {
				array_push( $sigh, "Error: Time limit should be specified if the test is a strict one." );
			}
		}
		
		$strict = ( empty($_POST['strict']) ) ? 0 : 1;
		$time_limit = ( empty($_POST['time_limit']) ) ? 0 : $_POST['time_limit'];
		
		if ( count( $sigh ) > 1 ) {
			echo json_encode( $sigh, JSON_HEX_TAG );
			exit;
		}
		
		# Ok, all set.
		$salt = "";
		$auth_key = crypt( mt_rand(), "kxkljl2092X#UEIJEkjsdlfOI" );
		$public = 1;
		$test_creator = get_user_id("");
		
		$db->query( sprintf("INSERT INTO test_details (test_title, test_purpose, strict_test, time_limit, auth_key, public, test_creator)
		                   values ( '%s','%s','%s','%s','%s','%s','%s' )", 
						   $_POST["test_name"],
						   $_POST["test_purpose"],
						   $strict,
						   $time_limit,
						   $auth_key,
						   $public,
						   $test_creator
						   ) 
			);
			
		$results = array( "success"	=>	"yes" );
		
		if ( $db->rows_affected == 1 ) {
			$test_id = $db->get_var(sprintf("SELECT test_id FROM test_details where auth_key='%s'", $auth_key ) );
			array_push( $results, sprintf("Test created. You can now <a href='%s?add_q&t_id=%s'> add </a>questions to it.", 
								$_SERVER['PHP_SELF'],
								$test_id
								));
		$_SESSION['t_id'] = $test_id;
		
		} else {
			array_push( $sigh, "Error: There was an error adding this test." );
		}
		
		if ( count( $sigh ) > 1 ) {
			echo json_encode( $sigh, JSON_HEX_TAG );
			exit; 
		}
		
		echo json_encode($results, JSON_HEX_TAG);
	}
}

/* 
 * Handles all the GET requests
 */
 
if ( isset ( $_GET ) ) {
	if ( isset( $_GET['add_q'] ) and isset( $_GET['t_id'] ) and ! empty ( $_GET['t_id'] ) ) {
		
		$test_id = $_GET['t_id'];
		
		if ( ! check_test_id( $db, $test_id ) ) {
			die ("Invalid test_id was passed or you don't have access to this test.");
		}
		
		get_header();
			$this_user = get_user_id( $_SESSION['user'] );
			
			$test_creator = get_test_owner( $db, $test_id );			
			if ( $this_user !== $test_creator ) {
				echo "You are not authorized to add questions to this test as you are 
					  " . $this_user . "where as test is owned by " . $test_creator;
			} else {
				$test_title = get_test_title( $db, $test_id );
				echo "Add questions to test: <strong>" . $test_title . "</strong>";
				
				if ( ! isset( $_SESSION ) ) {
					session_start();								
				}
				$_SESSION['t_id'] = $test_id;		
				
?>
				<a href="#" id="popout_aq">Add question</a>
				<div id="modal_popup">
					<h3>Add New Questions</h3>
					<br><label for="add_q_mul_choice">Multiple Choice Question</label>
					<input id="add_q_mul_choice" type="checkbox" style="cursor:pointer;" checked>
					
					<br><label for="add_q_match_following">Match the following</label>
					<input id="add_q_match_following" type="checkbox">
					
					<br><label for="add_fill_blanks">Fill in the blanks</label>
					<input id="add_fill_blanks" type="checkbox">
					
					<br><div id="insert_questions">Add Questions</div>
					<div id="cancel">Cancel</div>
				</div>
				
				
				<?php 
					$question_numbers = get_all_question_ids( $db, $test_id );
					if ( count($question_numbers) > 0 ) {
					?>
					<div id="existing_questions">
						<span>
				Edit questions:
				<?php
						for ( $counter = 0; $counter < count($question_numbers); $counter++ ) {
							printf("<a class='edit_question'  href='ajaxify.php?edit_question&t_id=%s&q_id=%s'>%s</a> ", $test_id, $question_numbers[$counter]["question_number"], $counter + 1);
							
						}
					}
					
				?>
						</span>
				</div>
							
				<div id="error_popup">
				</div>
				
				<div id="questions_deck">
					<div class="ia">
					</div>
					<input type="button" name="submit_questions" id="submit_questions" value="Submit Changes">
				</div>
				<div id="results">
				</div>
<?php
			}		
		get_footer();
	}
	
	
	
	if ( isset( $_GET['edit_question'] ) and ! empty ( $_GET['t_id'] ) and ! empty ( $_GET['q_id'] ) ) {
		if ( check_test_ownership( $db, $_GET['t_id'] ) ) {
			$t_id = $_GET['t_id'];
			$q_id = $_GET['q_id'];
		
			$question_title = get_question_title( $db, $t_id, $q_id );
			$question_type = get_question_type( $db, $t_id, $q_id );
			
			if ( $question_type == "multiple_choice" ) {
				printf("<div class='q_mul_choice question' q_mul_choice='1' id='question-%s'>", $q_id);
				printf ('<input type="text" class="q_title clearpix" name="q_title" placeholder="What is the title of your question?" value="%s">',$question_title);
				
				$mul_choice_answer_maker = get_mul_choice_answer_maker( $db, $t_id, $q_id );
				
				for( $counter = 0; $counter < count($mul_choice_answer_maker); $counter++ ) {
					printf ('<textarea name="ans_opt" class="mul_choice_ans_opt" placeholder="Answer option">%s</textarea>', $mul_choice_answer_maker[$counter]['choice_text']);
					if ( $mul_choice_answer_maker[$counter]["is_right_answer"] == 1 ) {
						printf(' <input type="checkbox" class="right_ans" name="right_ans" title="Mark this as right answer" checked>');
						printf(' <a title="Delete this answer option" class="delete_ans_option" href="#">Delete</a><br>');
					} else {
						printf(' <input type="checkbox" class="right_ans" name="right_ans" title="Mark this as right answer">');
						printf(' <a title="Delete this answer option" class="delete_ans_option" href="#">Delete</a><br>');
					}
				}
				printf('<div><a class="insert_mul_choice_answer_option" href="#">Insert Answer Option</a></div>');
				printf('<div><a class="delete_question" question="%s" href="#">Delete Question</a></div>', $q_id);
				printf("</div>");
			} 	elseif ( $question_type == "match_the_following" ) {
					printf ('<div class="q_match_following question clearpix" id="question-%s" q_match_following="1">', $q_id );
					printf ('<input type="text" class="q_title clearpix" name="q_title" placeholder="What is the title of your question?" value="%s">', $question_title );
					
					$match_following_answer_maker = get_match_following_answer_maker( $db, $t_id, $q_id );
					
					for ( $counter = 0; $counter < count($match_following_answer_maker); $counter++ ) {
						
						print('<div class="mapping"><div><a href="" class="del_mapping">Delete Mapping</a></div>');
							printf('<div class="left_column"><textarea type="text" class="left_option" placeholder="Left column option">%s</textarea> </div>', $match_following_answer_maker[$counter]["left_choice_text"]);
							printf('<div class="right_column"><textarea type="text" class="right_option" placeholder="Matching right column option">%s</textarea></div>', $match_following_answer_maker[$counter]["right_choice_text"]);							
						print('</div>');
					}
					
					print ('<a href="#"  class="insert_match_following_answer_option">Add Another Match</a>');
					printf('<div><a class="delete_question" question="%s" href="#">Delete Question</a></div>', $q_id);
					print("</div>");
			} else {
				echo "You cannot edit this question, or questions in this test as you don't own it.";
			}
		} 
	}
	
	if ( isset( $_GET['take_test'] ) and isset( $_GET['t_id'] ) and ! empty ( $_GET['t_id'] ) ) {
		$test_id = $_GET['t_id'];
		
		if ( check_test_ownership( $db, $test_id ) ) {
		get_header();
	
			$t_id = $_GET['t_id'];
			$all_questions = get_all_question_ids( $db, $test_id );
			
			foreach( $all_questions as $q_id ) {
				$q_id = $q_id['question_number'];
				
				$question_title = get_question_title( $db, $t_id, $q_id );
				$question_type = get_question_type( $db, $t_id, $q_id );
				
				if ( $question_type == "multiple_choice" ) {
					printf("<div class='q_mul_choice question' id='question-%s' q_type='%s'> ", $q_id, $question_type );
					printf ('<div class="q_title clearpix" name="q_title">%s</div>',$question_title);
					
					$mul_choice_answer_maker = get_mul_choice_answer_maker( $db, $t_id, $q_id );
					
					for( $counter = 0; $counter < count($mul_choice_answer_maker); $counter++ ) {
						$option = $counter + 1;
						printf('<div class="mc_ans_grp">');
						printf('<input type="checkbox" name="option-%s" class="mc_ans_chkbox" title="Choose %s as right answer">', $option, $option);
						printf ('<span name="ans_opt" class="mc_ans_text"> %s</span>', $mul_choice_answer_maker[$counter]['choice_text']);
						printf("</div>");
					}					
					printf("</div>");
				} elseif ( $question_type == "match_the_following" ) {
						printf ( '<div class="match_the_following question" id="question-%s" q_type="%s" >', $q_id, $question_type  );
						printf ( '<div type="text" class="q_title clearpix" name="q_title">%s</div>', $question_title );
						
						$match_following_answer_maker = get_match_following_answer_maker( $db, $t_id, $q_id );
						
						
						$left_used = array();
						$right_used = array();

						for ( $counter = 0; $counter < count( $match_following_answer_maker ); $counter++ ) {
						
								if ( ! isset($left_rand) ) {
									$left_rand = rand(0, count($match_following_answer_maker) - 1 );
								}
								
								if ( ! isset($right_rand) ) {
									$right_rand = rand(0, count($match_following_answer_maker) - 1);
								}
								
								while ( in_array( $left_rand, $left_used ) ) {
									$left_rand = rand(0, count($match_following_answer_maker) - 1 );
								}
								
								array_push($left_used, $left_rand);

								while ( in_array($right_rand, $right_used ) ) {
									$right_rand = rand(0, count($match_following_answer_maker) - 1);
								}
								
								array_push($right_used, $right_rand);

								printf('<div class="left_column"><div type="text" class="left_option" >%s</div> </div>', $match_following_answer_maker[$left_rand]["left_choice_text"]);
								
								printf('<div class="right_column"><div type="text" class="right_option" >%s</div></div>', $match_following_answer_maker[$right_rand]["right_choice_text"]);							
					}
					print('</div>');
				} else {
					echo "Unknown question_type!";
				}
			}
			print('<input type="button" id="submit_test" name="submit_test" value="Submit answers"><div class="results"></div>');
			
		get_footer();	
		} else {
			echo "Unauthorized user!";
			die();
		}		
	}
		
	if ( isset( $_GET['submit_test'] ) ) {	
		
		$test_id = $_POST['t_id'];
		echo "<pre>";
		var_dump($_POST);
		echo "</pre>";	
		if ( ! check_test_id( $db, $test_id ) ) {
			die ("Invalid test_id was passed or you don't have access to this test.");
		}
		
		if ( isset ( $_POST['multiple_choice'] ) ) {
			$mc = $_POST['multiple_choice'];
			for ( $q = 0; $q<count($mc); $q++ ) {
				$q_id = substr( $mc[$q]['q_identifier'], 9 );
				if ( ! get_question_title ( $db, $test_id, $q_id ) ) {	
					die("you seem to be doing something mischievious! Unknown question was sent");
				} else {
					# some basic credibility check passed.
					$selected_answers = $mc[$q]['selected_answers'];
					if ( $selected_answers == 0 ) {
						die ("How did you get here!?");
					} else {
						echo "hi";
					}
				}
			}
		}
		
		
		
		
		
		die();
		
		
	}
	
	
}
?>